import { defineStore } from "pinia";
import { AuthState } from "@/stores/interface";

import { SystemApi, BackStageApi } from "@/api/modules";
import { getFlatMenuList, getShowMenuList, getAllBreadcrumbList, getFormatUserMenu } from "@/utils";
import { useUserStore } from "./user";
import { useTenantStore } from "./tenant";

export const useAuthStore = defineStore({
  id: "auth",
  state: (): AuthState => ({
    // 按钮权限列表
    authButtonList: [],
    // 菜单权限列表
    authMenuList: [],
    // 当前页面的 router name，用来做按钮权限筛选
    routeName: "",
    showMenuList: [],
    curMenuList: [],
  }),
  getters: {
    // 按钮权限列表
    authButtonListGet: state => state.authButtonList,
    // 菜单权限列表 ==> 这里的菜单没有经过任何处理
    authMenuListGet: state => state.authMenuList,
    // 菜单权限列表 ==> 左侧菜单栏渲染，需要剔除 isHide == true
    showMenuListGet: state => getShowMenuList(state.authMenuList),
    // 菜单权限列表 ==> 扁平化之后的一维数组菜单，主要用来添加动态路由
    flatMenuListGet: state => getFlatMenuList(state.authMenuList),
    // 递归处理后的所有面包屑导航列表
    breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList),
  },
  actions: {
    // Get AuthButtonList
    async getAuthPermissionApi() {
      return new Promise(async resolve => {
        const res: any = await SystemApi.getUserProfile();
        let data = null;
        if (res.code == 200) {
          data = {
            permissions: res.permissions,
            user: res.user,
            roles: res.roles,
          };
        }

        this.authButtonList = data.permissions;
        const userStore = useUserStore();
        userStore.setUserPermission(data);
        // this.getTenantInfo(data.user.tenantId);
        resolve(data);
      });
    },

    async getTenantInfo(id: string) {
      // 租户信息
      const { data } = await BackStageApi.getTenantInfoApi(id);
      const tenantStore = useTenantStore();
      tenantStore.setTenantInfo(data);
    },

    // Get AuthMenuList
    async getAuthMenuList() {
      const { data } = await SystemApi.getRoutes();
      this.authMenuList = getFormatUserMenu(data as Menu.IMenu[]);
      this.showMenuList = getShowMenuList(data as Menu.MenuOptions[]);
    },
    // Set RouteName
    async setRouteName(name: string) {
      this.routeName = name;
    },
  },
});
